package com.zklh.leetcode.top100.problem114;

import com.zklh.leetcode.tree.model.TreeNode;

/**
 * @author Nelson
 * @Description 解法1
 * @create 2023-02-07 11:21
 */
public class Solution1 {
    public void flatten(TreeNode root) {
        flattenAndReturnLast(root);
    }

    public TreeNode flattenAndReturnLast(TreeNode root){
        if (root == null) {
            return null;
        }
        TreeNode left = root.left;
        TreeNode right = root.right;
        TreeNode now = root;
        now.left = null;
        // 展开左子树
        if (left != null) {
            TreeNode leftLast = flattenAndReturnLast(left);
            now.right = left;
            now = leftLast;
        }

        if (right != null) {
            TreeNode rightLast = flattenAndReturnLast(right);
            now.right = right;
            now = rightLast;
        }
        return now;
    }
}

